package org.gw.building.ctrl;

import org.gw.building.model.Slide;
import org.gw.building.repositories.SlideRepository;
import org.gw.ylc.base.context.RequestContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("slide")
public class SlideCtrl {

	@Autowired
	private SlideRepository slideRepository;

	@RequestMapping("getSlides")
	@ResponseBody
	public List<Slide> getSlides(String name) {
		return slideRepository.findByStatus(1);
	}

	@RequestMapping("querySlides")
	@ResponseBody
	public Page<Slide> querySlides(String name) {
		return slideRepository.query(name, RequestContextHolder.get().getPageRequest());
	}

	@RequestMapping("addSlide")
	@ResponseBody
	public Object addSlide(Slide slide) {
		slide.setScsj(new Date());
		return slideRepository.save(slide);
	}

	@RequestMapping("enableSlide")
	@ResponseBody
	public Object enableSlide(String id, boolean enable) {
		Slide slide = slideRepository.findOne(id);
		slide.setStatus(enable ? 1 : 0);
		return slideRepository.save(slide);
	}

	@RequestMapping("deleteSlide")
	@ResponseBody
	public Object deleteSlide(final String[] ids) {
		slideRepository.delete(new Iterable<Slide>() {
			@Override
			public Iterator<Slide> iterator() {
				List<Slide> slides = new ArrayList<Slide>();
				for (String id : ids) {
					Slide slide = new Slide();
					slide.setId(id);
					slides.add(slide);
				}
				return slides.iterator();
			}
		});
		return ids.length;
	}
}
